package com.micro.business.common.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * <P>AES加密工具类</P>
 *
 * @author 高仕立
 * @date 2019/8/1 9:05 AM
 * @since
 */
public class AESUtil {
    
    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param password 加密密码
     * @return
     */
    public static byte[] encrypt(final String content, final String password) {
        try {
            final SecretKey secretKey = getKey(password);
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            // 创建密码器
            final Cipher cipher = Cipher.getInstance("AES");
            final byte[] byteContent = content.getBytes("utf-8");
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, key);
            final byte[] result = cipher.doFinal(byteContent);
            // 加密
            return result;
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (final NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (final InvalidKeyException e) {
            e.printStackTrace();
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (final IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (final BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param password 加密密码
     * @return
     */
    public static String encryptString(final String content, final String password) {
        final byte[] result = encrypt(content, password);
        if (result != null) {
            return parseByte2HexStr(result);
        }
        return null;
    }
    
    /**
     * 解密
     *
     * @param content 待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(final byte[] content, final String password) {
        try {
            final SecretKey secretKey = getKey(password);
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            final Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            final byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (final NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (final InvalidKeyException e) {
            e.printStackTrace();
        } catch (final IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (final BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解密
     *
     * @param content 待解密内容
     * @param password 解密密钥
     * @return
     */
    public static String decryptString(final String content, final String password) {
        final byte[] result = decrypt(parseHexStr2Byte(content), password);
        if (result != null) {
            return new String(result);
        }
        return null;
    }
    
    public static SecretKey getKey(final String strKey) {
        try {
            final KeyGenerator _generator = KeyGenerator.getInstance("AES");
            final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            _generator.init(128, secureRandom);
            return _generator.generateKey();
        } catch (final Exception e) {
            throw new RuntimeException(" 初始化密钥出现异常 ");
        }
    }
    
    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(final byte buf[]) {
        final StringBuffer sb = new StringBuffer();
        for (final byte element : buf) {
            String hex = Integer.toHexString(element & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    
    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(final String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        final byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            final int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            final int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    
    public static void main(final String[] args) {
    
    }
}
